import getApiData from '@/services/cpasRequest';
import { nanoid10 } from '@/utils';
import { msgError } from '@/utils/msg';
import { Modal } from 'antd';
import { LoadOptions } from 'devextreme/data';
import { consts } from '../consts';
import { AccountInfo } from '../typing';
import { showErrorInfo } from './tools/dialogs';

//
export async function getChangeApiNameData(
  apiName: string,
  params: {
    dbname: string;
    Data_ID: string;
    otherWhere: string;
    displayOption?: boolean;
  },
) {
  if (!params.dbname) return [];
  const res = await getApiData(apiName, params);
  if (res.ok) {
    return Promise.resolve({
      data: res.data,
      success: true,
    });
  }
  return Promise.resolve({
    data: [],
    success: false,
  });
}

// 获取账套
export async function getAccountInfo(params: { dbname: string }) {
  if (!params.dbname) return [];
  const res = await getApiData('account.accountInfo.getDataList', params);
  if (res.ok) {
    return Promise.resolve({
      data: res.data,
      success: true,
    });
  }
  return Promise.resolve({
    data: [],
    success: false,
  });
}

/***
 * 获取真表名
 */
export function getRealTableName(tableName: string, params: { data_id: string }) {
  for (const key of Object.keys(params)) {
    tableName = tableName.replaceAll(`{${key}}`, (params as any)[key]);
  }
  return tableName;
}

/***
 * 获取真表名
 */
export function getRealTableName_sampleList(tableName: string, params: { data_id: string }) {
  for (const key of Object.keys(params)) {
    tableName = tableName.replaceAll(`{${key}}`, (params as any)[key]);
  }
  return tableName + '_sampleList';
}
// 获取账套
export async function getAccountInfoList(params: { dbname: string }): Promise<AccountInfo[]> {
  const res = await getApiData('account.accountInfo.getDataList', params);
  if (res.ok) {
    return res.data;
  }
  return [];
}
export function getNanoid10() {
  return nanoid10().replaceAll('[', '_').replaceAll(']', '_');
}
/**
 * 获取删除表格选择项
 * @param gridRef
 * @param setConfirmDelete
 * @returns
 */
export function getDeleteGridSelectRows(
  gridRef: any,
  setConfirmDelete: (value: boolean) => void,
  onFinished: (deleteRowKeys: any[]) => void,
) {
  const selectedRowKeys = gridRef.current.instance.getSelectedRowKeys();
  if (selectedRowKeys.length == 0) {
    return msgError('请选择一些行,再执行删除!');
  }
  setConfirmDelete && setConfirmDelete(false);
  Modal.confirm({
    content: `确定要删除 ${selectedRowKeys.length} 行吗?`,
    zIndex: 2000,
    centered: true,
    onOk: () => {
      onFinished && onFinished(selectedRowKeys);
      setConfirmDelete && setConfirmDelete(true);
    },
    onCancel: () => {
      setConfirmDelete && setConfirmDelete(true);
    },
  });
}
/**
 * 选中数字框 全部数字
 * @param e
 */
export function textBoxSelectAll(e: any) {
  if (
    e.component?._$textEditorInputContainer.length &&
    e.component?._$textEditorInputContainer[0].childNodes.length
  ) {
    e.component?._$textEditorInputContainer[0].childNodes[0].select();
  }
}
/**
 * 解决 dx-popup 标题有....的问题
 * @param e
 * @param width
 */
export function devPopupTitleRendered(e: any, width: string = '400px') {
  const titleElement: any = e.titleElement;
  try {
    titleElement.childNodes[0].childNodes[0].childNodes[0].style.maxWidth = width;
    titleElement.childNodes[0].childNodes[0].childNodes[0].style.width = width;
  } catch (error) {}
}

export function showNotDataMsg(msg: string) {
  if (msg) {
    if (msg.includes('Invalid object name') && msg.includes('..CW_PZB')) {
      const index = msg.indexOf('..CW_PZB');
      const dataId = msg.substring(index + 8, index + 8 + 4);
      Modal.destroyAll();
      showErrorInfo('', `${dataId}年还未转换数据，不能使用${dataId}年凭证表!`);
    } else {
      msgError(msg);
    }
  }
}
/**
 * 通过LoadOptions 获取分页信息
 * @param loadOptions
 * @returns
 */
export function getPageInfoByLoadOptions(loadOptions: LoadOptions) {
  const pageSize = loadOptions.take || consts.defaultSampePageSize;
  const pageIndex = (loadOptions.skip || 0) / pageSize;
  return { pageIndex, pageSize };
}
/**
 * 获取排序字段中不能排序的字段
 * @param sortFields
 * @returns
 */
export function getSortFiedsCantSort(sortFields: string) {
  if (!sortFields) return false;
  const cantSordFields = [
    'sampleFrequency',
    'sampleType',
    'rn',
    'isError',
    'errrorAmount',
    'errrorMemo',
    'wpIndex',
  ];
  return cantSordFields.some((item) => sortFields.includes(`[${item}]`));
}
